// 国家模型
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:safemap/safemap.dart';

class AreaCodeModel extends BaseData {
  final String countryCode;
  final String phoneCode;
  final String name;
  String? flag;

  AreaCodeModel({
    required this.countryCode,
    required this.phoneCode,
    required this.name,
    this.flag,
  });

  factory AreaCodeModel.fromJson(Map<String, dynamic> json) {
    SafeMap safeMap = SafeMap(json);
    final phoneCode = safeMap['phone_code'].string ?? '';
    AreaCodeModel model = AreaCodeModel(
      countryCode: safeMap['country_code'].string ?? '',
      phoneCode:
          "+${phoneCode.replaceFirst(RegExp(r'^0+'), '')}", // 移除 phoneCode 前面的0
      name: safeMap['name'].string ?? '',
    );
    model.flag ??= model._getFlag();
    return model;
  }

  String _getFlag() {
    // Country code is two-letter ISO code
    // Convert each letter to the corresponding regional indicator symbol
    // Regional indicator symbols are Unicode characters in the range 🇦 to 🇿
    const flagOffset = 0x1F1E6; // Regional indicator symbol A offset
    const asciiOffset = 0x41; // ASCII 'A' offset

    // Convert the two-letter country code to uppercase
    final countryCodeUpper = countryCode.toUpperCase();

    if (countryCodeUpper.length != 2) {
      return '';
    }

    // Convert the country code to regional indicator symbols
    try {
      final firstChar =
          countryCodeUpper.codeUnitAt(0) - asciiOffset + flagOffset;
      final secondChar =
          countryCodeUpper.codeUnitAt(1) - asciiOffset + flagOffset;

      return String.fromCharCode(firstChar) + String.fromCharCode(secondChar);
    } catch (e) {
      return '';
    }
  }

  Map<String, dynamic> toMap() {
    return {
      'countryCode': countryCode,
      'dialCode': phoneCode,
      'name': name,
      'flag': flag,
    };
  }

  @override
  String toString() {
    return 'AreaCodeModel{countryCode: $countryCode, phoneCode: $phoneCode, name: $name, flag: $flag}';
  }
}
